//购物车的功能和逻辑

// 获取元素
let emptyBox = document.querySelector('.empty')
let cartBox = document.querySelector('.cart')

// 先判断是否登录
const token = window.localStorage.getItem('token')
const id = window.localStorage.getItem('id')

// 判断id和token是否存在
setCart()
function setCart() {
    if (!token || !id) return window.location.href = './login.html'


    // 应该做的就是你
    getCartList()
}

async function getCartList() {
    // 发送请求获取购物车列表
    let res = await pAjax({
        url: 'http://localhost:8080',
        data: { id },
        dataType: 'json',
        headers: { 'authorization': token }
    })
    // console.log(res);

    // 判断code是不是等于1
    if (res.code !== 1) return window.location.href = './login.html'
    // 代码能执行到这里 说明是正处于登录状态

    if (res.cart.length === 0) {
        emptyBox.classList.add('active')
        cartBox.classList.remove('active')
    } else {
        emptyBox.classList.remove('active')
        cartBox.classList.add('active')
        // 渲染页面
        bindHtml(res.cart)
    }
}

function bindHtml(list) {
    // 这里就可以操作list这个数组 也就是添加到购物车中的数据
    // console.log(list);
    // 渲染页面

    /*
        通过我们的分析我们需要一些统计性的数据
        
    */
    //  总数量         总的选中数量     总的价格
    let totalNum = 0, totalSelect = 0, totalPrice = 0
    list.forEach(item => {
        if (item.is_select) {
            totalNum += item.cart_number
            totalSelect++
            totalPrice += item.cart_number * item.current_price
        }
    })

    let str = `
    <div class="top">
                全选: <input class="selectAll" type="checkbox" ${list.length === totalSelect ? 'checked' : ''}>
            </div>
            <ul class="center">
            `

    list.forEach(item => {
        str += `
            <li>
                <div class="select">
                    <input type="checkbox" class="select_item" ${item.is_select ? 'checked' : ''} data-id=${item.goods_id}>
                </div>
                <div class="show">
                    <img src="${item.img_small_logo}" alt="">
                </div>
                <div class="title">${item.title}</div>
                <div class="price">￥${item.current_price}</div>
                <div class="number">
                    <button class="sub" data-id=${item.goods_id}>-</button>
                    <input type="text" value="${item.cart_number}">
                    <button class="add" data-id=${item.goods_id}>+</button>
                </div>
                <div class="subPrice">￥${(item.cart_number * item.current_price).toFixed(2)}</div>
                <div class="del">
                    <button class="delBtn" data-id=${item.goods_id}>删除</button>
                </div>
            </li>
            `
    })
    str += `
            </ul>
            <div class="bottom">
                <p>共计${totalNum}件商品</p>
                <div>
                    <button class="clear" ${totalSelect === 0 ? 'disabled' : 0}>清空购物车</button>
                    <button class="delAll" ${totalSelect === 0 ? 'disabled' : 0}> 删除所有已选中</button >
                    <button class="pay">去支付</button>
                </div >
        <p>总价￥ ${totalPrice.toFixed(2)}</p>
        </div >
        `
    cartBox.innerHTML = str
}

// 处理我们页面上的点击事件
cartBox.addEventListener('click', async e => {
    e = e || window.event
    let target = e.target || e.srcElement

    // 全选实现
    if (target.className === 'selectAll') {
        // 获取type
        let type = target.checked ? 1 : 0
        let res = await pAjax({
            url: 'http://localhost:8080',
            method: 'POST',
            data: { id, type },
            dataType: 'json',
            headers: { 'authorization': token }
        })
        // console.log(res);
        if (res.code === 1) getCartList()
    }

    // 点击每一个小按钮
    if (target.className === 'select_item') {
        // 获取商品的id
        let goodsId = target.dataset.id - 0
        // 发送请求
        let res = await pAjax({
            url: 'http://localhost:8080',
            method: 'POST',
            data: { id, goodsId },
            dataType: 'json',
            headers: { 'authorization': token }
        })
        // console.log(res);
        if (res.code === 1) getCartList()
    }


    // 减少购买数量-
    if (target.className === 'sub') {
        let goodsId = target.dataset.id - 0
        let number = target.nextElementSibling.value - 0
        if (number <= 1) number = 1

        // 发送请求
        let res = await pAjax({
            url: 'http://localhost:8080',
            method: 'POST',
            data: { id, goodsId, number: number - 1 },
            dataType: 'json',
            headers: { 'authorization': token }
        })

        // console.log(res);
        if (res.code === 1) getCartList()
    }

    // 增加购买数量+

    if (target.className === 'add') {
        let goodsId = target.dataset.id - 0
        let number = target.previousElementSibling.value - 0
        // 发送请求
        let res = await pAjax({
            url: 'http://localhost:8080',
            method: 'POST',
            data: { id, goodsId, number: number + 1 },
            dataType: 'json',
            headers: { 'authorization': token }
        })

        // console.log(res);
        if (res.code === 1) getCartList()
    }
    // 删除某件商品
    if (target.className === 'delBtn') {
        let goodsId = target.dataset.id - 0
        let res = await pAjax({
            url: 'http://localhost:8080',
            data: { id, goodsId },
            dataType: 'json',
            headers: { 'authorization': token }
        })

        // console.log(res);
        if (res.code === 1) getCartList()

    }
    // 清空购物车
    if (target.className === 'clear') {
        let res = await pAjax({
            url: 'http://localhost:8080',
            data: { id },
            dataType: 'json',
            headers: { 'authorization': token }
        })
        // console.log(res);

        if (res.code === 1) getCartList()
    }


    // 删除已选中
    if (target.className === 'delAll') {
        let res = await pAjax({
            url: 'http://localhost:8080',
            data: { id },
            dataType: 'json',
            headers: { 'authorization': token }
        })

        // console.log(res);
        if (res.code === 1) getCartList()
    }
})

